package cn.itcast.service.impl;

import cn.itcast.entity.Result;
import cn.itcast.service.SmsService;
import cn.itcast.utils.SMSUtils;
import com.alibaba.dubbo.config.annotation.Service;
import com.aliyuncs.exceptions.ClientException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.time.Duration;

@Service
@Slf4j
public class SmsServiceImpl implements SmsService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 发送消息
     * @param phone
     * @return
     */
    public Result sendLoginCode(String phone) {

        //定义redisKey
        String key = "LOGIN_CODE"+phone;

        if(redisTemplate.hasKey(key)){

            return Result.builder().flag(false).build();
        }

        //获取随机验证码
//        String param = RandomUtils.nextInt(100000, 999999) + "";

        String param = "123456";
        //如果为空则发送验证码失败
        if(StringUtils.isEmpty(param)){

            return Result.builder().flag(false).build();
        }

        try {
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,phone,param);

            //将获取到的验证码存入redis
            redisTemplate.opsForValue().set(key,param, Duration.ofMinutes(10));

            return Result.builder().flag(true).build();
        } catch (ClientException e) {
            log.error("消息发送失败");
        }

        return Result.builder().flag(false).message("消息发送失败").build();
    }
}
